package com.crm.service.impl;


import com.crm.dto.ClueGainDto;
import com.crm.mapper.CluesMapper;
import com.crm.mapper.FollowMapper;
import com.crm.mapper.RuleMapper;
import com.crm.mapper.UserMapper;
import com.crm.entity.Clue;
import com.crm.entity.Follow;
import com.crm.entity.User;
import com.crm.result.CluePage;
import com.crm.result.PageResultTow;
import com.crm.service.ClueService;
import com.crm.vo.ClueANDFollowVo;
import com.crm.vo.DeptTreeVo;
import com.crm.vo.SysDept;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ClueServiceImpl implements ClueService {
    @Autowired
    private CluesMapper cluesMapper;
    @Autowired
    private FollowMapper followMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RuleMapper ruleMapper;


    public static final String clueKey = "CLUE:";

    @Override
    //数据一致性
    @Transactional
    public void insertClue(Clue clue) {
//        clue.setUserid();//默认当前登陆用户
        Long maxId = cluesMapper.selectMaxId();
        if (maxId == null){
            maxId = 1L;
        }else {
            maxId +=1L;
        }
        clue.setId(maxId);//补充id
        clue.setStatus(1);//默认1 待跟进
        clue.setFaketype(0);//默认0 不为伪线索
        clue.setTransfer(0);//默认为0，线索池
        cluesMapper.insertClue(clue);
        Follow follow = new Follow();
        Long maxFollowId = followMapper.selectMaxId();
        if (maxFollowId == null){
            maxFollowId = 1L;
        }else {
            maxFollowId +=1L;
        }
        follow.setId(maxFollowId);
        follow.setClueid(clue.getId());
        follow.setCreateBy(clue.getId());
        follow.setNew01(0);
        followMapper.insertFollow(follow);

        // 获取线索过期时间
        Integer limitTime = (Integer) redisTemplate.opsForHash().get("task", "limitTime");
        Integer limitTimeType = (Integer) redisTemplate.opsForHash().get("task", "limitTimeType");
        if (limitTime != null) {
            // 设置线索，过期时间存线索到redis
            switch (limitTimeType) {
                case 0:
                    redisTemplate.opsForValue().set(clueKey + clue.getId(), clue, limitTime, TimeUnit.HOURS);
                    break;
                case 1:
                    redisTemplate.opsForValue().set(clueKey + clue.getId(), clue, 24 * limitTime, TimeUnit.HOURS);
                    break;
                case 2:
                    redisTemplate.opsForValue().set(clueKey + clue.getId(), clue, 7 * 24 * limitTime, TimeUnit.HOURS);
                    break;
                default:
                    log.info("未知线索过期时限");
            }
        }
    }

    @Override
    public PageResultTow getClueListByPage(CluePage page) {
        if (page.getParams().get("beginCreateTime") != ""){
            page.setBeginCreateTime(page.getParams().get("beginCreateTime"));
        }else {
            page.setBeginCreateTime(null);
        }
        if (page.getParams().get("endCreateTime") != ""){
            page.setEndCreateTime(page.getParams().get("endCreateTime"));
        }else {
            page.setEndCreateTime(null);
        }
        List<Long> longs = userMapper.selectByName(page.getOwner());
        if (longs.size()==0){
            longs.add(-1L);
            page.setUserids(longs);
        }else {
            page.setUserids(longs);
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
//        List<Clue> clues = cluesMapper.selectCluesByCondition(page.getParams().getBeginCreateTime(),page.getParams().getEndCreateTime());
//        PageInfo<Clue> pageInfo = new PageInfo<>(clues);
        List<Clue> clues = cluesMapper.selectByConditions(page); // 直接传入 CluePage
        PageInfo<Clue> pageInfo = new PageInfo<>(clues);
        PageResultTow pageResultTow = new PageResultTow(200, "查询成功", null, pageInfo.getTotal(), pageInfo.getList());

        return pageResultTow;
    }

    @Override
    public ClueANDFollowVo getClueById(Long clueid) {
        Clue clueById = cluesMapper.getClueId(clueid);
        User user = new User();
        if (clueById.getUserid() == null || clueById.getUserid() == 0){//如果为空，则设置默认值1
//            clueById.setUserid(1);
//            cluesMapper.updateClue(clueById);
            user = userMapper.selectById(1);
        }else {
            user = userMapper.selectById(clueById.getUserid());
        }
        User assignBy = userMapper.selectById(clueById.getAssignby());
        // 非空检查
        if (user == null) {
            throw new RuntimeException("用户不存在，ID：" + clueById.getUserid());
            // 或者根据业务需求处理，例如设置默认值：clueANDFollowVo.setCreateBy("未知");
        }
        ClueANDFollowVo clueANDFollowVo = new ClueANDFollowVo();
        clueANDFollowVo.setCreateBy(user.getUserName());//归属人name
        clueANDFollowVo.setCreateTime(clueById.getCreateTime());//创建时间
        clueANDFollowVo.setUpdateTime(clueById.getUpdateTime());//跟进时间
        clueANDFollowVo.setId(clueById.getId());//线索id
        clueANDFollowVo.setName(clueById.getName());//线索name
        clueANDFollowVo.setPhone(clueById.getPhone());//线索电话
        clueANDFollowVo.setChannel(clueById.getChannel());//渠道id
        clueANDFollowVo.setActivityId(clueById.getActivityId());//活动id
        clueANDFollowVo.setSex(clueById.getSex());//性别
        clueANDFollowVo.setAge(clueById.getAge());//活动年龄
        clueANDFollowVo.setWeixin(clueById.getWeixin());//微信号
        clueANDFollowVo.setQq(clueById.getQq());//qq号
        clueANDFollowVo.setStatus(clueById.getStatus());//线索状态
        clueANDFollowVo.setOwner(user.getUserName());//归属人name
//        clueANDFollowVo.setAssignBy(assignBy.getUserName());//跟进人name
        return clueANDFollowVo;
    }

    @Override
    public List<DeptTreeVo> getUserListSelect(Integer deptId) {
        List<SysDept> deptList = cluesMapper.selectAllDepts(deptId);
        List<DeptTreeVo> deptTreeVos = buildDeptTree(deptList);
        return deptTreeVos;
    }

    @Override
    public void putAssignment(ClueGainDto clueGainDto) {
        cluesMapper.putAssignment(clueGainDto);
    }

    private List<DeptTreeVo> buildDeptTree(List<SysDept> deptList) {
        Map<Long, DeptTreeVo> map = new HashMap<>();
        deptList.forEach(dept -> {
            DeptTreeVo vo = new DeptTreeVo();
            vo.setId(dept.getDeptId());
            vo.setLabel(dept.getDeptName());
            vo.setChildren(new ArrayList<>());
            map.put(dept.getDeptId(), vo);
        });
        List<DeptTreeVo> rootList = new ArrayList<>();

        deptList.forEach(dept -> {
            DeptTreeVo current = map.get(dept.getDeptId());
            if (dept.getParentId() == null || dept.getParentId() == 0) {
                rootList.add(current);
            } else {
                DeptTreeVo parent = map.get(dept.getParentId());
                if (parent != null) {
                    parent.getChildren().add(current);
                }
            }
        });

        return rootList;
    }
}
